package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptios.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import com.leyou.search.constants.SearchConstants;
import com.leyou.search.dto.SearchParamDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.entity.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.stream.Collectors;

import static com.leyou.search.constants.SearchConstants.*;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    private final GoodsRepository repository;

    private final ItemClient itemClient;

    public SearchServiceImpl(GoodsRepository repository, ItemClient itemClient) {
        this.repository = repository;
        this.itemClient = itemClient;
    }

    @Override
    public void createIndexAndMapping() {
        // TODO 判断是否存在，如果存在，你再删除
        // TODO 删除以前的索引库
        try {
            repository.deleteIndex();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建索引库和映射
        repository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": false\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }

    @Override
    public void loadData() {
        // 初始化分页信息
        int page = 1, rows = 100;

        while (true) {
            log.info("开始第{}页数据导入!", page);
            // 批量查询SPU数据
            PageDTO<SpuDTO> result = itemClient.querySpuByPage(page, rows, true, null, null, null);
            List<SpuDTO> items = result.getItems();

            // 把数据封装成Goods
            List<Goods> goodsList = items.parallelStream().map(this::buildGoods).collect(Collectors.toList());

            // 把数据写入Elasticsearch
            repository.saveAll(goodsList);

            log.info("第{}页数据导入成功!", page);
            // 判断是不是最后一页
            if (page >= result.getTotalPage()) {
                // 最后一页了，没了，结束
                log.info("数据导入结束，共导入{}页数据!", page);
                break;
            }
            // 翻页
            page++;
        }
    }

    @Override
    public Mono<List<String>> getSuggestion(String key) {
        // 准备模板参数
        Map<String, Object> params = new HashMap<>();
        params.put(SUGGESTION_PARAM_PREFIX_KEY, key);
        params.put(SUGGESTION_PARAM_FIELD, SUGGESTION_FIELD);
        // 查询模板
        return repository.suggestByTemplate(SUGGESTION_TEMPLATE_ID, params);
    }

    @Override
    public Mono<PageInfo<Goods>> searchGoods(SearchParamDTO param) {
        // 1.构建查询条件的工厂对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 1.1.source过滤
        sourceBuilder.fetchSource(DEFAULT_SOURCE_FIELD, new String[0]);
        // 1.2.查询条件
        QueryBuilder basicQuery = buildBasicQuery(param);
        sourceBuilder.query(basicQuery);
        // 1.3.分页条件
        sourceBuilder.from(param.getFrom());
        sourceBuilder.size(param.getSize());
        // 1.4.排序条件
        if (StringUtils.isNotBlank(param.getSortBy())) {
            // 排序字段存在，才去排序
            sourceBuilder.sort(param.getSortBy(), param.getDesc() ? SortOrder.DESC : SortOrder.ASC);
        }
        // 1.5.高亮条件
        sourceBuilder.highlighter(new HighlightBuilder().field(DEFAULT_SEARCH_FIELD)
                .preTags(DEFAULT_PRE_TAG).postTags(DEFAULT_POST_TAG));

        // 2.查询
        return repository.queryBySourceBuilderForPageHighlight(sourceBuilder);
    }

    @Override
    public Mono<Map<String, List<?>>> searchFilters(SearchParamDTO param) {
        // 1.构建查询条件的工厂对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 1.1.查询条件
        QueryBuilder basicQuery = buildBasicQuery(param);
        sourceBuilder.query(basicQuery);

        // 1.2.分页设置为0，不需要商品数据，只要聚合结果
        sourceBuilder.size(0);

        // 2.添加聚合条件
        // 2.1.分类的聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("categoryAgg").field(CATEGORY_FIELD_NAME));
        // 2.2.品牌的聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("brandAgg").field(BRAND_FIELD_NAME));
        // 2.3.规格参数nested聚合
        sourceBuilder.aggregation(
                // nested聚合
                AggregationBuilders.nested("specAgg", SPEC_FIELD_PATH)
                        // 嵌套名称的聚合
                        .subAggregation(AggregationBuilders.terms("nameAgg").field(SPEC_NAME_FIELD_NAME)
                                // 嵌套对value的聚合
                                .subAggregation(AggregationBuilders.terms("valueAgg").field(SPEC_VALUE_FIELD_NAME))
                        )
        );
        // 3.查询
        Mono<Aggregations> mono = repository.aggregationBySourceBuilder(sourceBuilder);

        // 4.解析结果
        return mono.map(this::parseAggregationsResult);
    }

    @Override
    public void saveGoodsById(Long spuId) {
        // 需要spu
        SpuDTO spu = itemClient.queryGoodsById(spuId);
        // 构建goods
        Goods goods = buildGoods(spu);
        // 写入索引库
        repository.save(goods);
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        repository.deleteById(spuId);
    }

    private QueryBuilder buildBasicQuery(SearchParamDTO param) {
        String key = param.getKey();
        if (StringUtils.isBlank(key)) {
            // 搜索条件为null，返回异常
            throw new LyException(400, "搜索条件不能为空！");
        }
        // 1.准备一个布尔查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // 2.添加match查询，查询标题
        queryBuilder.must(QueryBuilders.matchQuery(SearchConstants.DEFAULT_SEARCH_FIELD, key));

        // 3.添加filter查询，过滤参数查询， {品牌: 18374, CPU频率: "2.0-2.5GHz", 分类: 76}
        Map<String, String> filters = param.getFilters();
        // 3.1.判断是否有过滤项
        if(!CollectionUtils.isEmpty(filters)){
            // 3.2.有数据，我们遍历map，添加过滤项
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                // 3.2.1.获取key
                String name = entry.getKey();
                // 3.2.2.判断当前过滤参数是什么，品牌？分类？其它？
                if("品牌".equals(name)){
                    queryBuilder.filter(QueryBuilders.termQuery(BRAND_FIELD_NAME, entry.getValue()));
                } else if("分类".equals(name)){
                    queryBuilder.filter(QueryBuilders.termQuery(CATEGORY_FIELD_NAME, entry.getValue()));
                } else {
                    // 3.2.3.规格参数，采用nested查询，需要把specs.name和specs.value形成布尔查询
                    BoolQueryBuilder specQueryBuilder = QueryBuilders.boolQuery();
                    // 匹配参数名称，例如：CPU频率
                    specQueryBuilder.must(QueryBuilders.termQuery(SPEC_NAME_FIELD_NAME, name));
                    // 匹配参数值，例如："2.0-2.5GHz"
                    specQueryBuilder.must(QueryBuilders.termQuery(SPEC_VALUE_FIELD_NAME, entry.getValue()));
                    // 添加nested查询
                    queryBuilder.filter(QueryBuilders.nestedQuery(SPEC_FIELD_PATH, specQueryBuilder, ScoreMode.None));
                }
            }
        }
        return queryBuilder;
    }

    private Map<String, List<?>> parseAggregationsResult(Aggregations aggregations){
        // 1.创建一个Map结果
        Map<String, List<?>> filters = new LinkedHashMap<>();

        // 2.解析分类聚合结果
        // 2.1.根据名称获取聚合结果
        Terms categoryAgg = aggregations.get("categoryAgg");
        // 2.2.获取buckets,从buckets中解析出分类id的集合
        List<Long> categoryIds = categoryAgg.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
        // 2.3.根据分类的id查询分类的对象
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(categoryIds);
        // 2.4.存入filters
        filters.put("分类", categories);

        // 3.解析品牌聚合结果
        // 3.1.根据名称获取聚合结果
        Terms brandAgg = aggregations.get("brandAgg");
        // 3.2.获取buckets,从buckets中解析出分类id的集合
        List<Long> brandIds = brandAgg.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
        // 3.3.根据品牌的id查询品牌的对象
        List<BrandDTO> brands = itemClient.queryBrandByIds(brandIds);
        // 3.4.存入filters
        filters.put("品牌", brands);

        // 4.解析规格参数聚合结果
        // 4.1.根据名称获取聚合结果
        Nested specAgg = aggregations.get("specAgg");
        // 4.2.获取对规格参数名称的聚合结果
        Terms nameAgg = specAgg.getAggregations().get("nameAgg");
        // 4.3.获取buckets，并且遍历
        for (Terms.Bucket bucket : nameAgg.getBuckets()) {
            // 4.3.1.从bucket中获取key，就是规格参数的名称
            String specName = bucket.getKeyAsString();
            // 4.3.2.获取当前规格参数的值的聚合结果
            Terms valueAgg = bucket.getAggregations().get("valueAgg");
            // 4.3.3.从valueAgg中获取buckets，并解析其中的key
            List<String> values = valueAgg.getBuckets()
                    .stream()
                    .map(Terms.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            // 4.3.4.放入filters
            filters.put(specName, values);
        }
        return filters;
    }

    private Goods buildGoods(SpuDTO spu) {
        // 1.自动补全字段，包含：名称、分类、品牌
        List<String> suggestion = new ArrayList<>();
        suggestion.add(spu.getName());
        suggestion.add(spu.getBrandName());
        // 利用StringUtils工具中的方法，截取字符串中最后一个'/'之后的部分。xxx/yyy/zzz 中的 zzz
        suggestion.add(StringUtils.substringAfterLast(spu.getCategoryName(), "/"));

        // 2.规格参数，包含规格参数键值对
        // 2.1.查询规格参数键值对
        List<SpecParamDTO> params = itemClient.querySpecsValues(spu.getId(), true);
        // 2.2.准备结果的集合
        List<Map<String, Object>> specs = new ArrayList<>();
        // 2.3.遍历，并把SpecParamDTO中的name和value取出，放入map中
        for (SpecParamDTO param : params) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", param.getName());
            // 判断param是否是数值类型param.getNumeric()，有没有包含segment，
            // 如果有，判断value在segment中的哪个区间，用区间覆盖原本的value
            map.put("value", chooseSegment(param));// 5.2
            specs.add(map);
        }

        // 3.spu下的sku的销量的和
        // 3.1.查询sku
        List<SkuDTO> skuDTOList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuDTOList)) {
            skuDTOList = itemClient.querySkuBySpuId(spu.getId());
        }
        // 3.2.计算sku的销量和
        // 准备价格集合
        Set<Long> prices = new TreeSet<>();
        long sold = 0;
        for (SkuDTO sku : skuDTOList) {
            // 3.3.计算销量和
            sold += sku.getSold();
            // 获取价格
            prices.add(sku.getPrice());
        }

        // 5.spu下的某个sku的图片
        String image = StringUtils.substringBefore(skuDTOList.get(0).getImages(), ",");

        // 封装Goods并返回
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        // 自动补全字段，包含：名称、分类、品牌
        goods.setSuggestion(suggestion);
        // 规格参数，包含规格参数键值对
        goods.setSpecs(specs);
        // spu下的sku的销量的和
        goods.setSold(sold);
        goods.setTitle(spu.getTitle() + " " + spu.getBrandName() + " " + spu.getCategoryName());
        // spu下的sku的价格集合
        goods.setPrices(prices);
        // spu下的某个sku的图片
        goods.setImage(image);
        goods.setCategoryId(spu.getCid3());
        goods.setBrandId(spu.getBrandId());
        goods.setId(spu.getId());

        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }
}
